import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import React, { useState, useEffect, useRef, useMemo } from "react";

const FileUploadButton = ({ onTextUpdate }) => {
  const fileInputRef = useRef(null);

  const handleButtonClick = () => {
    fileInputRef.current.click(); // 触发隐藏的input点击
  };

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      console.log("Selected file:", file);
      // 这里可以添加文件处理逻辑（如上传、预览等）
      const reader = new FileReader();
      reader.onload = (e) => {
        console.log("onload complete");
        onTextUpdate(e.target.result); // 读取文件内容后更新文本
      };
      reader.readAsText(file); // 读取文件为文本
    }
  };

  return (
    <div>
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        style={{ display: "none" }} // 隐藏原生input
        accept=".txt" // 可选：限制文件类型
      />

      <Button
        variant="contained"
        component="label"
        onClick={handleButtonClick}
        color="primary"
      >
        选择本地文件
        {/* 隐藏原生input的伪label方案（可选） */}
      </Button>
    </div>
  );
};
function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setCount((prevCount) => prevCount + 1); // 每秒更新一次状态
    }, 1000);

    return () => clearInterval(interval); // 清理定时器
  }, []); // 空依赖数组，表示只在组件挂载和卸载时执行

  return <p>计时器：{count} 秒</p>;
}

function TextViewer({ content, chunkSize = 1024 }) {
  const [visibleContent, setVisibleContent] = useState("");
  const [startIndex, setStartIndex] = useState(0);
  const containerRef = useRef(null);

  // 初始化显示第一部分内容
  useEffect(() => {
    if (content) {
      setVisibleContent(content.slice(0, chunkSize));
    }
  }, [content]);
  // const visibleContent = content.slice(0, startIndex + chunkSize);

  // 处理滚动事件
  const handleScroll = () => {
    if (!containerRef.current || !content) return;

    const { scrollTop, clientHeight, scrollHeight } = containerRef.current;
    const threshold = 100; // 距离底部100px时加载更多

    // 如果接近底部，加载更多内容
    if (scrollTop + clientHeight > scrollHeight - threshold) {
      const nextIndex = startIndex + chunkSize;
      if (nextIndex < content.length) {
        setVisibleContent(content.slice(0, nextIndex + chunkSize));
        setStartIndex(nextIndex);
      }
    }
  };

  return (
    <div>
      <h3>文件内容：</h3>
      <div
        ref={containerRef}
        onScroll={handleScroll}
        style={{
          marginTop: "20px",
          padding: "10px",
          border: "1px solid #ddd",
          borderRadius: "5px",
          background: "#f9f9f9",
          maxWidth: "100%",
          maxHeight: "75vh",
          overflow: "auto", // 改为auto以启用滚动
        }}
      >
        <pre style={{ margin: 0 }}>
          {visibleContent || "暂无内容"}
          {startIndex + chunkSize < content.length && <div>加载中...</div>}
        </pre>
      </div>
    </div>
  );
}
function TextViewerScroll({ content, lineHeight = 20, visibleLines = 30 }) {
  const [scrollTop, setScrollTop] = useState(0);
  const containerRef = useRef(null);
  const contentRef = useRef(null);

  // 预处理内容为行数组（如果尚未是数组）
  const lines =
    typeof content === "string" ? content.split("\n") : content || [];

  // 计算总高度（用于虚拟滚动）
  const totalHeight = lines.length * lineHeight;

  // 计算当前可见的起始行和结束行
  const startLine = Math.max(0, Math.floor(scrollTop / lineHeight) - 5);
  const endLine = Math.min(
    lines.length,
    startLine + visibleLines + 10 // 多渲染一些作为缓冲
  );

  // 可见的行内容
  const visibleLinesContent = lines.slice(startLine, endLine).join("\n");

  // 处理滚动
  const handleScroll = () => {
    if (containerRef.current) {
      setScrollTop(containerRef.current.scrollTop);
    }
  };

  return (
    <div>
      <h3>文件内容：</h3>
      <div
        ref={containerRef}
        onScroll={handleScroll}
        style={{
          marginTop: "20px",
          border: "1px solid #ddd",
          borderRadius: "5px",
          background: "#f9f9f9",
          maxWidth: "100%",
          maxHeight: "75vh",
          overflow: "auto",
          position: "relative",
        }}
      >
        {/* 虚拟滚动容器 */}
        <div style={{ height: `${totalHeight}px`, position: "relative" }}>
          {/* 实际渲染的内容（只渲染可见部分） */}
          <pre
            ref={contentRef}
            style={{
              position: "absolute",
              top: `${startLine * lineHeight}px`,
              left: "10px",
              right: "10px",
              margin: 0,
              lineHeight: `${lineHeight}px`,
            }}
          >
            {visibleLinesContent || "暂无内容"}
          </pre>
        </div>

        {/* 加载指示器 */}
        {lines.length === 0 && <div>加载中...</div>}
      </div>
    </div>
  );
}

export function Home() {
  const [text, setText] = useState("");

  return (
    <Box
      sx={{
        width: "100%",
        overflow: "hidden", // 禁止滚动条
        p: 2,
      }}
    >
      <FileUploadButton onTextUpdate={setText} />
      {/* <TextViewer content={text} chunkSize={8 * 1024} /> */}
      <TextViewerThirdPart content={text} />
    </Box>
  );
}
